package com.bjpowernode.dataservice.service;

import com.bjpowernode.commons.exception.YLBException;
import com.bjpowernode.commons.service.UserService;
import com.bjpowernode.dataservice.mapper.UserMapper;
import com.bjpowernode.commons.model.User;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;

@DubboService
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Value("${salt}")
    private String salt;

    public boolean checkPhone(String phone) {
        return userMapper.checkPhone(phone);
    }

    public void register(String phone, String password) {
        if (checkPhone(phone)) {
            throw new YLBException("该手机已被注册！");
        }
        // 对密码进行MD5加密处理，保证安全
        // 使用数据库反向查询(碰撞破解法（王小云）)的方式，还是能够被破解的，不够安全
        //password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 加盐处理，使其更安全
        password = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        System.out.println(password);
        userMapper.register(phone, password, new Date());
    }

    public User login(String phone, String password) {

        // 根据手机号查询用户对象，如果查询不到，则提示该手机没有注册
        User user = userMapper.getUserByPhone(phone);
        if (user == null) {
            throw new YLBException("该手机没有注册！");
        }

        // 判断密码
        String pwd1 = user.getLoginPassword();
        String pwd2 = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        if (!pwd1.equals(pwd2)) {
            throw new YLBException("密码不正确！");
        }

        return user;
    }

    public User login(String phone) {
        User user = userMapper.getUserByPhone(phone);
        if (user == null) {
            throw new YLBException("该手机没有注册！");
        }

        return user;
    }

    public void auth(Long id, String name, String idcard) {
        userMapper.auth(id, name, idcard);
    }

    public void updateLoginTime(Long id, Date date) {
        userMapper.updateLoginTime(id, date);
    }

    public void updateHeaderImage(Long id, String headerImage) {
        userMapper.updateHeaderImage(id, headerImage);
    }
}
